<template>
  <div>
    <div class="hello" v-for="item in 3" :key="item">
      <div style="width: 80%;height: 30vh;overflow-y: scroll;border: 1px solid #ccc;margin-left: 10%;">
        <div style="width: 100%;height: 80vh;">
          <h1 :ref="setScrollElement">controller{{ item }}</h1>
        </div>
      </div>
      <h1 v-show="!visible">_</h1>
      <h1 v-show="visible">{{ msg }}</h1>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      visible: true,
      scrollElements: []
    }
  },
  mounted() {
    this.observeScroll();
  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect();
    }
  },
  methods: {
    setScrollElement(el) {
      if (el) {
        this.scrollElements.push(el);
      }
    },
    observeScroll() {
      const options = {
        root: null, // 相对于视口
        rootMargin: '0px',
        threshold: 0.1 // 当元素有10%出现在视口中时触发
      };

      const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            this.visible = false;
          } else {
            this.visible = true;
          }
        });
      }, options);

      this.scrollElements.forEach(el => {
        observer.observe(el);
      });
      this.observer = observer;
    }
  }
}
</script>